package com.atguigu.gulimall.search.thread;

import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * 异步编排-任务组合，一个完成即可
 *
 * @author LaiSanShan
 * @date 2021-08-18
 */
public class CompletableFuture4Test {
    private static ExecutorService threadPool = Executors.newFixedThreadPool(10);

    public static void main(String[] args) throws ExecutionException, InterruptedException {
        System.out.println("main启动。。。");
        // 1.
//        CompletableFuture<Integer> completableFuture1 = CompletableFuture.supplyAsync(() -> {
//            System.out.println("任务1执行。。。返回1");
//            return 1;
//        }, threadPool);
//        CompletableFuture<Integer> completableFuture2 = CompletableFuture.supplyAsync(() -> {
////            try {
////                Thread.sleep(10000000);
////            } catch (InterruptedException e) {
////                e.printStackTrace();
////            }
//            System.out.println("任务2执行。。。返回2");
//            return 2;
//        }, threadPool);
//        completableFuture1.runAfterEither(completableFuture2, () -> {
//            System.out.println("任务3执行。。。");
//        });
        // 2.
//        CompletableFuture<Integer> completableFuture1 = CompletableFuture.supplyAsync(() -> {
//            System.out.println("任务1执行。。。返回1");
//            return 1;
//        }, threadPool);
//        CompletableFuture<Integer> completableFuture2 = CompletableFuture.supplyAsync(() -> {
//            System.out.println("任务2执行。。。返回2");
//            return 2;
//        }, threadPool);
//        completableFuture1.acceptEither(completableFuture2, (res) -> {
//            System.out.println("任务3执行。。。" + res);
//        });
        // 3.
        CompletableFuture<Integer> completableFuture1 = CompletableFuture.supplyAsync(() -> {
            System.out.println("任务1执行。。。返回1");
            return 1;
        }, threadPool);
        CompletableFuture<Integer> completableFuture2 = CompletableFuture.supplyAsync(() -> {
            try {
                Thread.sleep(3000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println("任务2执行。。。返回2");
            return 2;
        }, threadPool);
        CompletableFuture<Integer> completableFuture = completableFuture1.applyToEither(completableFuture2, (res) -> {
            System.out.println("任务3执行。。。返回res：" + res + "+1");
            return res + 1;
        });
        Integer res = completableFuture.get();
        System.out.println("最终结果：" + res);

        System.out.println("main结束。。。");
    }

}
